package com.company.clientscard.shared.proxyManager;

import java.util.List;

import com.company.clientscard.shared.proxy.DocumentProxy;
import com.company.clientscard.shared.requestfactory.DocumentRequestFactory;
import com.company.clientscard.shared.requestfactory.DocumentRequestFactory.DocumentRequestContext;
import com.google.gwt.core.client.GWT;
import com.google.gwt.view.client.HasData;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class DocumentProxyManager implements ProxyManager<DocumentProxy> {

	private DocumentRequestContext context;

	public void refreshDisplays(HasData<DocumentProxy> display) {
		display.setVisibleRangeAndClearData(display.getVisibleRange(), true);
	}

	public void initContext() {
		DocumentRequestFactory factory = GWT
				.create(DocumentRequestFactory.class);
		factory.initialize(new SimpleEventBus());
		context = factory.context();
	}

	@Override
	public void add(DocumentProxy object, final HasData<DocumentProxy> display) {
		// TODO Auto-generated method stub
		context.save(object).fire(new Receiver<Void>() {

			@Override
			public void onSuccess(Void response) {
				// TODO Auto-generated method stub
				refreshDisplays(display);
			}
		});
	}

	@Override
	public void update(DocumentProxy object,
			final HasData<DocumentProxy> display) {
		context.update(object).fire(new Receiver<DocumentProxy>() {

			@Override
			public void onSuccess(DocumentProxy response) {
				refreshDisplays(display);
			}
		});

	}

	@Override
	public void setObjectList(final int firstRow, int numberOfRows,
			final HasData<DocumentProxy> display) {
		initContext();
		context.findWithExpression(firstRow, numberOfRows, null, null).fire(
				new Receiver<List<DocumentProxy>>() {

					@Override
					public void onSuccess(List<DocumentProxy> response) {
						// TODO Auto-generated method stub
						display.setRowData(firstRow, response);
					}
				});

	}

	@Override
	public DocumentProxy getProxyObject() {
		initContext();
		DocumentProxy object = context.create(DocumentProxy.class);
		return object;
	}

	@Override
	public DocumentProxy getProxyObject(DocumentProxy object) {
		initContext();
		DocumentProxy editibleObject = context.edit(object);
		return editibleObject;
	}

}
